import { ref, watch, onMounted } from 'vue'
import { defineStore } from 'pinia'
import { weatherApi } from '@/api/api'

export const useCityItemStore = defineStore('CityItem', () => {
    const cityList = ref([])
    const showCity = ref(null)
    const showCityWeather = ref(null)
    const isLoading = ref(false)
    const hasError = ref(false)

    const setShowCity = async (name, adcode) => {
        if (!adcode) return
        
        isLoading.value = true
        hasError.value = false
        showCity.value = null
        showCityWeather.value = null
        
        try {
            const [weatherRes, forecastRes] = await Promise.all([
                weatherApi.getCurWeather(adcode),
                weatherApi.getWeather(adcode)
            ])
            
            const weather = weatherRes.data.lives && weatherRes.data.lives[0]
            const forecasts = forecastRes.data.forecasts && forecastRes.data.forecasts[0]
            
            if (!weather || !forecasts) {
                throw new Error('无效的城市数据')
            }
            
            showCity.value = { adcode, name, weather }
            showCityWeather.value = forecasts.casts
        } catch (error) {
            console.error('获取城市天气数据失败:', error)
            hasError.value = true
            showCity.value = null
            showCityWeather.value = null
        } finally {
            isLoading.value = false
        }
    }

    const addCity = () => {
        if (!showCity.value) return
        
        // 检查是否已存在相同城市
        const existingCity = cityList.value.find(item => item.adcode === showCity.value.adcode)
        if (!existingCity) {
            cityList.value.push(showCity.value)
        }
    }

    const removeCity = (adcode) => {
        cityList.value = cityList.value.filter(item => item.adcode !== adcode)
    }

    const updateCity = async (cities) => {
        if (!cities || cities.length === 0) return
        
        try {
            // 使用Promise.all进行并行请求
            const promises = cities.map(async (item) => {
                try {
                    const res = await weatherApi.getCurWeather(item.adcode)
                    if (res.data.lives && res.data.lives[0]) {
                        item.weather = res.data.lives[0]
                    }
                    return item
                } catch (error) {
                    console.error(`更新${item.name}天气数据失败:`, error)
                    return item // 保留原始数据
                }
            })
            
            const updatedCities = await Promise.all(promises)
            cityList.value = updatedCities
        } catch (error) {
            console.error('更新城市天气数据失败:', error)
        }
    }

    const getCityWeather = async (adcode) => {
        if (!adcode) {
            return { success: false, error: '缺少城市编码' }
        }
        
        isLoading.value = true
        hasError.value = false
        showCity.value = null
        showCityWeather.value = null
        
        try {
            // 并行获取当前天气和天气预报
            const [weatherRes, forecastRes] = await Promise.all([
                weatherApi.getCurWeather(adcode),
                weatherApi.getWeather(adcode)
            ])
            
            // 检查API响应有效性
            if (!weatherRes.data || !weatherRes.data.lives || weatherRes.data.lives.length === 0) {
                throw new Error('无效的天气数据')
            }
            
            if (!forecastRes.data || !forecastRes.data.forecasts || forecastRes.data.forecasts.length === 0) {
                throw new Error('无效的天气预报数据')
            }
            
            const cityInfo = weatherRes.data.lives[0]
            const forecasts = forecastRes.data.forecasts[0]
            
            showCity.value = { 
                adcode, 
                name: cityInfo.city, 
                weather: cityInfo 
            }
            showCityWeather.value = forecasts.casts
            
            return { success: true }
        } catch (error) {
            console.error('获取城市天气预报失败:', error)
            hasError.value = true
            showCity.value = null
            showCityWeather.value = null
            return { success: false, error }
        } finally {
            isLoading.value = false
        }
    }

    // 清除显示城市的数据
    const clearShowCity = () => {
        showCity.value = null
        showCityWeather.value = null
        hasError.value = false
    }

    // 监听cityList的变化，保存到localStorage
    watch(cityList, () => {
        localStorage.setItem('cities', JSON.stringify(cityList.value))
    }, { deep: true })

    // 组件挂载时从localStorage读取城市列表
    onMounted(() => {
        try {
            if (localStorage.getItem('cities')) {
                const cities = JSON.parse(localStorage.getItem('cities'))
                cityList.value = Array.isArray(cities) ? cities : []
                
                if (cityList.value.length > 0) {
                    updateCity(cityList.value)
                }
            }
        } catch (error) {
            console.error('读取本地存储城市数据失败:', error)
            cityList.value = []
        }
    })

    return {
        cityList,
        showCity,
        showCityWeather,
        isLoading,
        hasError,
        getCityWeather,
        addCity,
        removeCity,
        setShowCity,
        clearShowCity
    }
})
